class GreedSnake {
  container = document.querySelector("#container");
  snakeHead = document.querySelector(".snake-head");
  snakeBodys = [...document.querySelectorAll(".snake-body")];
  slowBtn = document.querySelector(".slow");
  middleBtn = document.querySelector(".middle");
  fastBtn = document.querySelector(".fast");
  suspendBtn = document.querySelector(".suspend");
  refreshBtn = document.querySelector(".refresh");
  scoreDom = document.querySelector(".score");
  snakePosition = { x: 0, y: 0 };
  snakeOldPosition = { x: 0, y: 0 };
  snakePositionMax = {
    x: this.container.offsetWidth - this.snakeHead.offsetWidth - 2,
    y: this.container.offsetHeight - this.snakeHead.offsetHeight - 2,
  };
  direction = "right";
  food = null;
  foodPosition = {};
  foodImgs = ["food1.webp", "food2.webp", "food3.jpeg"];
  speed = 200;
  score = 0;

  constructor() {
    // 绑定键盘操作
    this.bind();
    this.createFood();
    this.play();
  }

  bind() {
    document.addEventListener("keydown", (e) => {
      switch (e.key) {
        case "ArrowLeft":
          if (this.direction !== "right") {
            this.direction = "left";
          }
          break;
        case "ArrowRight":
          if (this.direction !== "left") {
            this.direction = "right";
          }
          break;
        case "ArrowUp":
          if (this.direction !== "down") {
            this.direction = "up";
          }
          break;
        case "ArrowDown":
          if (this.direction !== "up") {
            this.direction = "down";
          }
          break;
        default:
          break;
      }
    });

    this.slowBtn.onclick = () => {
      clearInterval(this.gameSuspend);
      this.speed = 700;
      this.play();
    };
    this.middleBtn.onclick = () => {
      clearInterval(this.gameSuspend);
      this.speed = 300;
      this.play();
    };
    this.fastBtn.onclick = () => {
      clearInterval(this.gameSuspend);
      this.speed = 50;
      this.play();
    };

    this.suspendBtn.onclick = (e) => {
      if (this.suspendBtn.textContent === "暂停") {
        clearInterval(this.gameSuspend);
        this.suspendBtn.innerHTML = "继续";
      } else {
        clearInterval(this.gameSuspend);
        this.play();
        this.suspendBtn.innerHTML = "暂停";
      }
    };
    this.refreshBtn.onclick = () => {
      location.reload();
    };
  }

  play() {
    this.gameSuspend = setInterval(() => {
      // 蛇头自动前进
      this.move();
      //蛇身跟随移动
      this.followMove();
      //监听死亡
      this.die();
    }, this.speed);
  }

  move() {
    // 记录蛇头上一步的坐标
    this.snakeOldPosition.x = this.snakePosition.x;
    this.snakeOldPosition.y = this.snakePosition.y;
    // 蛇头向指定方向走一步
    switch (this.direction) {
      case "right":
        this.snakePosition.x = this.snakePosition.x + 20;
        break;
      case "left":
        this.snakePosition.x = this.snakePosition.x - 20;
        break;
      case "up":
        this.snakePosition.y = this.snakePosition.y - 20;
        break;
      case "down":
        this.snakePosition.y = this.snakePosition.y + 20;
        break;
      default:
        break;
    }

    // 边界监测;
    if (this.snakePosition.x > this.snakePositionMax.x) {
      this.snakePosition.x = 0;
    }
    if (this.snakePosition.x < 0) {
      this.snakePosition.x = this.snakePositionMax.x;
    }
    if (this.snakePosition.y > this.snakePositionMax.y) {
      this.snakePosition.y = 0;
    }
    if (this.snakePosition.y < 0) {
      this.snakePosition.y = this.snakePositionMax.y;
    }

    // 吃到食物检测
    if (
      this.snakePosition.x === this.foodPosition.x &&
      this.snakePosition.y === this.foodPosition.y
    ) {
      // 先删除原有的蛋
      this.container.removeChild(this.food);
      // 创建一个新的蛋;
      this.createFood();
      // 让蛇身变长;
      this.createSnakeBody();
      //分数加1
      this.score++;
      this.scoreDom.innerHTML = `分数：${this.score}`;
    }

    // 赋值
    this.snakeHead.style.left = `${this.snakePosition.x}px`;
    this.snakeHead.style.top = `${this.snakePosition.y}px`;
  }

  followMove() {
    // 让蛇身体的最后一节跟随着蛇头移动;
    const snakeBodyLast = this.snakeBodys[this.snakeBodys.length - 1];
    snakeBodyLast.style.left = `${this.snakeOldPosition.x}px`;
    snakeBodyLast.style.top = `${this.snakeOldPosition.y}px`;
    //剩下的每一节都跟上前一节
    this.snakeBodys.forEach((item, index, arr) => {
      if (index < arr.length - 1) {
        item.style.left = arr[index + 1].style.left;
        item.style.top = arr[index + 1].style.top;
      }
    });
  }

  createFood() {
    // 随机位置，可以和蛇头重合
    this.foodPosition = {
      x: Math.round((this.snakePositionMax.x / 20) * Math.random()) * 20,
      y: Math.round((this.snakePositionMax.y / 20) * Math.random()) * 20,
    };

    // 创建一个元素;
    this.food = document.createElement("div");
    // 给元素添加类名;
    this.food.className = "food";
    //给元素加背景
    this.food.style.backgroundImage = `url("./img/${this.getExtract(
      this.foodImgs
    )}")`;
    // 给元素加上随机位置;
    this.food.style.left = this.foodPosition.x + "px";
    this.food.style.top = this.foodPosition.y + "px";
    // 放入容器之中;
    this.container.appendChild(this.food);
  }

  //   随机取食物
  getExtract(array) {
    const random = (min, max) => Math.floor(Math.random() * (max - min) + min); //随机数方法
    let index = random(0, array.length); //生成一个从最小值为0 最大值为数组长度的随机数
    return array[index];
  }

  createSnakeBody() {
    let snakeBody = document.createElement("div");
    snakeBody.className = "snake-body";
    // 把新创建出来的蛇身体放进数组之中;
    this.snakeBodys.push(snakeBody);
    // 蛇的新身体放入到容器之中;
    this.container.appendChild(snakeBody);
  }

  die() {
    // 遍历数组之中所有的元素;
    this.snakeBodys.forEach((ele) => {
      // ele 代表每一个蛇身体元素;
      if (
        parseInt(ele.style.left) === this.snakePosition.x &&
        parseInt(ele.style.top) === this.snakePosition.y
      ) {
        clearInterval(this.gameSuspend);
        if (confirm("死了，是否重新开始")) {
          location.reload();
        } else {
        }
      }
    });
  }
}

new GreedSnake();
